var express = require('express');
var router = express.Router();
var multiparty = require('multiparty');
var verifyToken = require('./token');
var jwt=require('jsonwebtoken')
var {usersModel,rolesModel,menuModel}=require('../../database/user.js')
/* GET home page. */
router.post('/login',async function(req, res, next) {
  const {name,password,lastLogin}=req.body
  console.log(name,password);
  try{
    let info=await usersModel.find({name,password}).populate('role_id')
    // console.log(info,'info');
    if(info.length){
      // console.log(info[0].role_id.permissions,'231');
      let menu=await menuModel.find({_id:info[0].role_id.permissions})
      let token=jwt.sign({menu:menu},'abc',{expiresIn:'10m'})
      // console.log(token);
      res.send({
        code: 200,
        token,
        menu,
        user: info[0], // 新增，返回当前登录用户信息
        message: '登录成功'
      })
    }else{
      res.send({
        code:400
      })
    }
  }catch(err){
    console.log(err);
    res.send({
      code:500
    })
  }
});

router.get('/user', verifyToken, async (req, res) => {
  let user = []
  if (req.query.key) {
    user = await usersModel.find({ name: { $regex: req.query.key, $options: 'i' } }).populate('role_id')
  } else {
    user = await usersModel.find().populate('role_id')
  }
  res.send({
    code: 200,
    data: user,
    message: '无'
  })
})

router.delete('/del', verifyToken, async (req, res) => {
  await usersModel.deleteOne({ _id: req.query._id })
  res.send({
    code: 200,
  })
})

router.post('/add', verifyToken, async (req, res) => {
  await usersModel.create(req.body)
  res.send({
    code: 200,
  })
})

router.put('/upd', verifyToken, async (req, res) => {
  await usersModel.updateOne({ _id: req.body._id }, req.body)
  res.send({
    code: 200,
  })
})

router.get('/role', verifyToken, async (req, res) => {
  let role = await rolesModel.find()
  res.send({
    code: 200,
    data: role
  })
})

router.post('/nologin', verifyToken, async (req, res) => {
  let {name,lastLogin}=req.body
  await usersModel.updateOne({name},{$set:{lastLogin:lastLogin}})
  res.send({
    code: 200,
  })
})

router.get('/time', verifyToken, async (req, res) => {
  let {name}=req.query
  let info=await usersModel.findOne({name})
  console.log(info.lastLogin);
  
  res.send({
    code: 200,
    time:info.lastLogin
  })
})
module.exports=router
